package com.zygh.lz.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zygh.lz.constant.SystemCon;
import com.zygh.lz.dao.SptypeMapper;
import com.zygh.lz.dao.XlevelserviceMapper;
import com.zygh.lz.entity.Sptype;
import com.zygh.lz.entity.Xlevelservice;
import com.zygh.lz.service.SptypeService;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.vo.ResultBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SptypeServiceImpl implements SptypeService {

    @Resource
    private SptypeMapper sptypeMapper;

    @Resource
    private XlevelserviceMapper xlevelserviceMapper;


    @Override
    public List<Sptype> selectSptypeInfo(Integer type) {
        return sptypeMapper.selectSptypeInfo(type);

    }

    @Override
    public ResultBean addSPtype(Sptype sptype) {
        int insert = sptypeMapper.insert(sptype);
        return ResultUtil.execOp(insert, "新增");
    }

    @Override
    public ResultBean updateSPtype(Sptype sptype) {
        int update = sptypeMapper.updateById(sptype);
        return ResultUtil.execOp(update, "修改");
    }

    @Override
    public ResultBean deleteSPtype(Integer id) {
        List<Integer> primaryKeys = new ArrayList<>();
        Sptype one = new Sptype();

        List<Sptype> sptypes = sptypeMapper.selectList(Wrappers.<Sptype>lambdaQuery().eq(Sptype::getPid, id));
        List<Integer> ids = sptypes.stream().map(Sptype::getId).collect(Collectors.toList());

        one.setYxzt(0);
        ids.add(id);
        do {
            primaryKeys.addAll(ids);
            // sptypeMapper.update(one,Wrappers.<Sptype>lambdaQuery().in(Sptype::getId,ids));
            List<Sptype> childrenSptype = sptypeMapper.selectList(Wrappers.<Sptype>lambdaQuery().in(Sptype::getPid, ids));
            ids = childrenSptype.stream().map(Sptype::getId).collect(Collectors.toList());

            List<Xlevelservice> xlevelservices = xlevelserviceMapper.selectList(Wrappers.<Xlevelservice>lambdaQuery().in(Xlevelservice::getPositionId, primaryKeys));
            if (CollUtil.isNotEmpty(xlevelservices)) {
                return ResultUtil.setError(SystemCon.RERROR1, "该类型下有岗位，不能直接删除", null);
            }
            if (CollUtil.isNotEmpty(ids)) {
                return ResultUtil.setError(SystemCon.RERROR1, "该勤务类型下包含子级，请先删除子级！", null);
            }
        } while (CollUtil.isNotEmpty(ids));

        int delete = sptypeMapper.delete(Wrappers.<Sptype>lambdaQuery().in(Sptype::getId, primaryKeys));

        return ResultUtil.execOp(delete, "删除");
    }

    @Override
    public ResultBean findDropDown() {
        return ResultUtil.setOK("成功", sptypeMapper.findDropDown());
    }

}
